package com.nanfang51g3.ckz.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JsPromptResult;
import android.webkit.JsResult;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.nanfang51g3.ckz.R;
import com.nanfang51g3.ckz.ui.base.Base2Activity;
import com.nanfang51g3.ckz.ui.base.IPresenter;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.HostJsScope;
import com.nanfang51g3.ckz.ui.webView.webviewcallback.InjectedChromeClient;
import com.nanfang51g3.ckz.utils.AppManager;
import com.nanfang51g3.ckz.utils.ImageUtil;
import com.nanfang51g3.ckz.utils.KLog;
import com.nanfang51g3.ckz.utils.NetUtils;

import org.json.JSONObject;

import java.io.File;

public class H5WebView extends Base2Activity implements ReWebChomeClient.OpenFileChooserCallBack {
    private WebView public_web_view;
    private String assets_error_url = "file:///android_asset/app/index.html";
    private String assets_success_url = "file:///android_asset/app/index.html";
    private ProgressBar progressBar;
    private WebSettings webSettings;
    private String id_url;
    private int id_title;
    private String title;
    Context context;

    @Override
    public IPresenter getPresenter() {
        return null;
    }

    @Override
    public int getContentView() {
        return R.layout.public_web_view;
    }

    @Override
    public boolean isShowLeftIcon() {
        return true;
    }

    @Override
    public boolean isShowRightIcon() {
        return false;
    }

    @Override
    public int setLeftIcon() {
        return R.mipmap.ic_accounting_left;
    }

    @Override
    public int setRightIcon() {
        return 0;
    }

    @Override
    public int showTitle() {
        return id_title;
    }

    @Override
    public void onClickLeft(View v) {
        KLog.i("Evd","onClickLeft");
        if (public_web_view.canGoBack()) {
            KLog.i("Evd","if");
            public_web_view.goBack();
        } else {
            KLog.i("Evd","else");
            AppManager.getAppManager().finishActivity(this);
        }



    }

    @Override
    public void onClickRight(View v) {

    }

    @Override
    public void onIntent() {
        super.onIntent();
        id_url = getIntent().getStringExtra("id_url");
        id_title = getIntent().getIntExtra("id_title", 0);
    }

    private static final String TAG = "MyActivity";
    private static final int REQUEST_CODE_PICK_IMAGE = 0;
    private static final int REQUEST_CODE_IMAGE_CAPTURE = 1;
    private ValueCallback<Uri> mUploadMsg;
    private Intent mSourceIntent;

    @Override
    public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
        mUploadMsg = uploadMsg;
        showOptions();
    }private class ReOnCancelListener implements DialogInterface.OnCancelListener {

        @Override
        public void onCancel(DialogInterface dialogInterface) {
            if (mUploadMsg != null) {
                mUploadMsg.onReceiveValue(null);
                mUploadMsg = null;
            }
        }
    }
    public void showOptions() {
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
        alertDialog.setOnCancelListener(new ReOnCancelListener());
        alertDialog.setTitle(R.string.options);
        alertDialog.setItems(R.array.options, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            mSourceIntent = ImageUtil.choosePicture();
                            startActivityForResult(mSourceIntent, REQUEST_CODE_PICK_IMAGE);
                        } else {
                            mSourceIntent = ImageUtil.takeBigPicture();
                            startActivityForResult(mSourceIntent, REQUEST_CODE_IMAGE_CAPTURE);
                        }
                    }
                }
        );
        alertDialog.show();
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_IMAGE_CAPTURE:
            case REQUEST_CODE_PICK_IMAGE: {
                try {
                    if (mUploadMsg == null) {
                        return;
                    }
                    String sourcePath = ImageUtil.retrievePath(this, mSourceIntent, data);
                    if (TextUtils.isEmpty(sourcePath) || !new File(sourcePath).exists()) {
                        KLog.w(TAG, "sourcePath empty or not exists.");
                        break;
                    }
                    Uri uri = Uri.fromFile(new File(sourcePath));
                    mUploadMsg.onReceiveValue(uri);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this;
        public_web_view = (WebView) findViewById(R.id.public_web_view);
        progressBar = (ProgressBar) findViewById(R.id.index_progressBar);
        progressBar.setMax(100);
        public_web_view.loadUrl(id_url);
        setWebView();
    }

    public Context getContext() {
        return this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        public_web_view.reload();


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        public_web_view.destroy();
        public_web_view.setVisibility(View.INVISIBLE);

    }

    private void fixDirPath() {
        String path = ImageUtil.getDirPath();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    public void setWebView() {
        fixDirPath();
        webSettings = public_web_view.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setSupportZoom(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setAllowFileAccess(true);// 设置允许访问文件数据
//        webSettings.setUseWideViewPort(true);//点击操作扩大缩小
        webSettings.setLoadWithOverviewMode(true);
//        webSettings.setBuiltInZoomControls(true);//缩小指针
        webSettings.setDatabaseEnabled(true);
//        CustomChromeClient customChromeClient = new CustomChromeClient("injs", HostJsScope.class);
        public_web_view.setWebChromeClient(new ReWebChomeClient(this));
        public_web_view.setWebViewClient(new WebViewClient() {

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                progressBar.setVisibility(View.VISIBLE);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                public_web_view.loadUrl(assets_error_url);
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                super.onReceivedSslError(view, handler, error);
            }
        });
    }

    /**
     * 继承Injected 必须重写的方法
     */
    class CustomChromeClient extends InjectedChromeClient {

        public CustomChromeClient(String injectedName, Class injectedCls) {
            super(injectedName, injectedCls);
            // TODO Auto-generated constructor stub
        }

        @Override
        public boolean onJsAlert(WebView view, String url, String message,
                                 final JsResult result) {
            // TODO Auto-generated method stub
            return super.onJsAlert(view, url, message, result);
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            // TODO Auto-generated method stub
            progressBar.setProgress(newProgress);
            if (newProgress >= 100) {
                progressBar.setVisibility(View.GONE);
            }
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public boolean onJsPrompt(WebView view, String url, String message,
                                  String defaultValue, JsPromptResult result) {
            // TODO Auto-generated method stub
            try {
                JSONObject json = new JSONObject(message);
                KLog.i("Evd", json.toString());//获取数据判断调用js方法
                if (json.optString("method").equals("reloadWebView")) {
                    if (NetUtils
                            .checkNetworkInfo(getContext())) {
                        public_web_view.loadUrl(id_url);
                    } else {
                        Toast.makeText(getContext(), "您的网络已断开,请重新连接网络",
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();

            } finally {

            }

            return super.onJsPrompt(view, url, message, defaultValue, result);
        }
    }
}
